package com.run.guifeng.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.run.guifeng.dao.AdminUserMapper;
import com.run.guifeng.model.entity.AdminUser;
import com.run.guifeng.model.enums.ServiceResultEnum;
import com.run.guifeng.service.AdminUserService;
import com.run.guifeng.util.MD5Util;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author sky
 */
@Service
public class AdminUserServiceImpl implements AdminUserService {

    @Resource
    private AdminUserMapper adminUserMapper;

    @Override
    public AdminUser login(String userName, String password) {
        String passwordMd5 = MD5Util.MD5Encode(password, "UTF-8");
        return adminUserMapper.selectOne(Wrappers.<AdminUser>lambdaQuery()
                .eq(AdminUser::getUserName, userName).eq(AdminUser::getPasswordMd, passwordMd5)
                .eq(AdminUser::getLocked, false));
    }

    /**
     *
     * @param loginUserId
     * @return
     */
    @Override
    public AdminUser getUserDetailById(Integer loginUserId) {
        return adminUserMapper.selectById(loginUserId);
    }

    @Override
    public String updatePassword(Integer loginUserId, String originalPassword, String newPassword) {
        AdminUser adminUser = adminUserMapper.selectById(loginUserId);
        //当前用户非空才可以进行更改
        if (adminUser != null) {
            String originalPasswordMd5 = MD5Util.MD5Encode(originalPassword, "UTF-8");
            String newPasswordMd5 = MD5Util.MD5Encode(newPassword, "UTF-8");
            //比较原密码是否正确
            if (originalPasswordMd5.equals(adminUser.getPasswordMd())) {
                //设置新密码并修改
                adminUser.setPasswordMd(newPasswordMd5);
                adminUser.setUpdateTime(new Date());
                if (adminUserMapper.updateById(adminUser) > 0) {
                    //修改成功则返回true
                    return ServiceResultEnum.SUCCESS.getResult();
                }
            }
        }
        return ServiceResultEnum.DATA_NOT_EXIST.getResult();
    }

    @Override
    public String updateName(Integer loginUserId, String loginUserName) {
        AdminUser adminUser = adminUserMapper.selectById(loginUserId);
        //当前用户非空才可以进行更改
        if (adminUser != null) {
            //设置新名称并修改
            adminUser.setUserName(loginUserName);
            adminUser.setUpdateTime(new Date());
            if (adminUserMapper.updateById(adminUser) > 0) {
                //修改成功则返回true
                return ServiceResultEnum.SUCCESS.getResult();
            }
        }
        return ServiceResultEnum.DATA_NOT_EXIST.getResult();
    }
}
